package com.baizhi.controller;

import com.baizhi.annotations.MyAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;

@RestController
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload.dir}")
    private String realPath;

    /**
     * 第二种文件上传
     * 注意: 推荐使用这种方式, 因为上传路径在配置文件中定义，更加解耦。不用修改程序
     *      0.打印原始文件的大小，名称，类型
     *      1. 为文件重命名，新文件的名称
     *      2. 将上传文件放到哪个地方， 自己通过配置文件指定目录
     */
    @RequestMapping("uploadByJarDeploy")
    @MyAdvice
    public String uploadByJarDeploy(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}",originalFilename);
        log.info("原始文件大小：{}",file.getSize());
        log.info("原始文件类型：{}",file.getContentType());

        String ext = getFileExtension(originalFilename);
        String newFileName = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + "lzm";
        File targetFile = new File(realPath + newFileName + "." + ext);
        file.transferTo(targetFile);
        return  "上传成功";
    }

    private static String getFileExtension(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    }


    /**
     * 方式二：
     * 获取项目中某个目录的绝对路径，然后将上传文件放到该目录
     *
     */
    @RequestMapping("upload")
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {//定义:接收文件对象 multipartFile file变量名要与form中input type="file"标签name属性名一致
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}",originalFilename);
        log.info("原始文件大小：{}",file.getSize());
        log.info("原始文件类型：{}",file.getContentType());

        String ext = getFileExtension(originalFilename);
        String newFileName = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now()) + "lzm";

        String filePath = request.getServletContext().getRealPath("/upload");
        File targetFile = new File(filePath + File.separator + newFileName + "." + ext);
        file.transferTo(targetFile);
        return  "上传成功";
    }
}
